import http from "./interface";
import {
  getToken,
  setToken,
  clearToken,
} from "@/utils/vmeitime-http/localStorage.js";

// var graceJS = require('@/GraceUI5/js/grace.js');

http.interceptor.request = async (config) => {
  config.header = {
    "Content-Type": "application/json",
    charset: "UTF-8",
    "X-Requested-With": "XMLHttpRequest",
    Authorization: "Bearer " + (await getToken()),
  };

  uni.showToast({
    title: "加载中",
    icon: "loading",
    mask: true,
    duration: 500,
  });
};

http.interceptor.response = (response) => {
  const data = response.data;
  const code = data?.code;

  //后端未检验jwt的均无code 未走中间件
  uni.hideLoading();
  if (response.statusCode === 422) {
    uni.showToast({
      title: response.data.message,
      icon: "none",
    });
    return new Promise(() => {});
  }
  if (response.statusCode === 500)
    uni.showModal({
      title: "提示",
      content: `服务器出现错误,请联系客服`,
      confirmText: "确定",
      confirmColor: "#3CC51F",
    });

  switch (code) {
    case 200:
      return data.data;
    case 0: {
      uni.showModal({
        title: data.msg,
        showCancel: false,
      });
      return Promise.reject(data.msg);
    }
    case 100000: {
      uni.showModal({
        title: data.msg,
        showCancel: false,
      });
      return new Promise(() => {});
    }
    case 1: {
      return data.message;
    }
    case -1: {
      uni.showModal({
        title: data.msg,
        showCancel: false,
      });
      return null;
    }
    case 401: {
      // //再次进入如果有用户信息和token 续费token
      clearToken();
      return new Promise(() => {});
    }
    case 100003: {
      clearToken();
      uni.navigateTo({
        url: `/pages/login/login`,
      });
      return new Promise(() => {});
    }
    case 100007: {
      uni.showModal({
        title: data.msg,
        showCancel: false,
        success: () => {
          uni.navigateBack();
        },
      });
      return new Promise(() => {});
    }
    case 100040: {
      uni.showModal({
        title: data.msg,
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: `/pages/login/login`,
            });
          }
        },
      });
      return new Promise(() => {});
    }
    default: {
      if (data.meta) return data;
      return data.data;
    }
  }
  return response;
};

export default http;
